import {isString} from "./Helpers";
import GlobalData from "../../store/GlobalData";

export class Http {
    // protected api = 'http://www.tree.com/api/';

    protected api = 'http://api.tree.lib.wiki/api/';

    async request(url: string, method: string = 'GET', params?: any, headers: any = {}) {
        return new Promise<any>((resolve, reject) => {
            const xhr = cc.loader.getXMLHttpRequest();
            xhr.open(method, this.api + url, true);
            xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
            const userToken = cc.sys.localStorage.getItem('userToken')
            if (userToken) {
                xhr.setRequestHeader("Authorization", `Bearer ${userToken}`);
            }
            for (let i in headers) {
                let header = headers[i];
                if (typeof header === 'string' && typeof i === 'string') {
                    xhr.setRequestHeader(i, header);
                }
            }
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4 && (xhr.status >= 200 && xhr.status <= 207)) {
                    if (xhr.status === 206) {
                        const token = xhr.getResponseHeader('token') || ''
                        GlobalData.userToken = token
                        cc.sys.localStorage.setItem('userToken', token)
                    }

                    let response: any = xhr.responseText
                    if (isString(response)) {
                        response = JSON.parse(response);
                    }
                    if (response.code === 200) {
                        resolve(response);
                    } else {
                        if (response.code === 401 || response.code === 208) {
                            GlobalData.userToken = null
                            GlobalData.userInfo = {}
                            cc.sys.localStorage.setItem('userToken', '')
                            cc.director.loadScene('login')
                        }
                        reject(response)
                    }

                }
            };
            xhr.send(JSON.stringify(params));
        })

    }

    async get(url: string, params?: any, headers: any = {}) {
        params = Object.assign({}, params)
        url += '?'
        for (let i in params) {
            url += `${i}=${params[i]}&`
        }
        return this.request(url, 'GET', params, headers)
    }

    async post(url: string, params?: any, headers: any = {}) {
        return this.request(url, 'POST', params, headers)
    }

}

export const http: Http = new Http
